from sqlalchemy import (
    BigInteger,
    Boolean,
    Column,
    Integer,
    DECIMAL,
    SMALLINT,
    String,
    LargeBinary
)
from sqlalchemy.orm import relationship

from models.base import AuditBase, IdBase


class Blog(AuditBase):
    title = Column(String(255), nullable=True, comment="博客标题")
    top_value = Column(Integer, nullable=True, comment="置顶值 越大越靠前")
    is_great = Column(Boolean, nullable=True, comment="是否是精品 0否1是")
    category_id = Column(BigInteger, nullable=True, comment="博客类别")
    summary = Column(String(255), nullable=True, comment="博客内容概要")
    content_id = Column(BigInteger, nullable=True, comment="博客内容")
    word_count = Column(Integer, nullable=True, comment="字数统计")
    read_duration = Column(DECIMAL(10, 2), nullable=True, comment="阅读时长")

    category = relationship(
        "BlogCategory",
        back_populates="blogs",
        primaryjoin="foreign(Blog.category_id) == BlogCategory.id"
    )

    content = relationship(
        "BlogContent",
        back_populates="blog",
        primaryjoin="foreign(Blog.content_id) == BlogContent.id"
    )

    visits = relationship(
        "BlogVisit",
        back_populates="blog",
        primaryjoin="Blog.id == foreign(BlogVisit.blog_id)"
    )

    comments = relationship(
        "BlogComment",
        back_populates="blog",
        primaryjoin="Blog.id == foreign(BlogComment.blog_id)"
    )


class BlogCategory(AuditBase):
    name = Column(String(45), nullable=True, comment="类别名称")

    blogs = relationship(
        "Blog",
        back_populates="category",
        primaryjoin="BlogCategory.id == foreign(Blog.category_id)"
    )


class BlogContent(IdBase):
    content = Column(LargeBinary, comment="博客内容")

    blog = relationship(
        "Blog",
        back_populates="content",
        primaryjoin="BlogContent.id == foreign(Blog.content_id)"
    )


class BlogVisit(AuditBase):
    ip = Column(String(255), nullable=True, comment="ip地址")
    os = Column(String(255), nullable=True, comment="操作系统")
    browser = Column(String(255), nullable=True, comment="浏览器")
    uri = Column(String(255), nullable=True, comment="路径")
    blog_id = Column(BigInteger, nullable=True, comment="博客id")

    blog = relationship(
        "Blog",
        back_populates="visits",
        primaryjoin="foreign(BlogVisit.blog_id) == Blog.id"
    )


class BlogComment(AuditBase):
    blog_id = Column(BigInteger, comment="博客id")
    parent_id = Column(BigInteger, comment="父评论id")
    name = Column(String(255), comment="评论人昵称")
    website = Column(String(255), nullable=True, comment="评论人网站")
    ip_address = Column(String(45), nullable=True, comment="评论人ip")
    user_agent = Column(String(255), nullable=True, comment="评论人浏览器信息")
    content = Column(String(512), comment="评论内容")
    is_approved = Column(SMALLINT, comment="是否通过")

    blog = relationship(
        "Blog",
        back_populates="comments",
        primaryjoin="foreign(BlogComment.blog_id) == Blog.id"
    )
